<template>
  <div class="mobile-preview" ref="mobileRef">
    <div ref="thumbnailListRef"
      :class="{ 'thumbnail-list': true, 'thumbnail-list_heiwx': platform === 'wx' && isCanIExportIt === true, 'thumbnail-list_hei': platform != 'wx' || isCanIExportIt === false }">
      <div class="thumbnail-item" v-for="(slide, index) in slides" :key="slide.id">
        <!-- <ThumbnailSlide
          :slide="slide"
          :size="screenWidth - 20"
          :visible="index < slidesLoadLimit"
        /> -->
        <!-- <ThumbnailSlide v-if="sfType !== '1'" :slide="slide" v-if="sfType === '1'"
          :size="index > 0 ? screenWidth / 2.05 - 10 : screenWidth - 20" :visible="index < slidesLoadLimit" /> -->
        <ThumbnailSlide :slide="slide" :size="screenWidth - 20" :visible="index < slidesLoadLimit" />
        <div class="page_number">{{ index + 1 }}</div>
      </div>
    </div>
    <div class="hint">
      <IconAttention class="iconA" />使用电脑浏览器访问可以编辑作品，体验更完整功能
    </div>
    <div class="menu" v-if="platform === 'wx' && isCanIExportIt === true">
      <!-- <div class="menu-item" @click="changeMode('editor')">
        <IconEdit class="icon" /> 编辑
      </div>
      <Divider type="vertical" style="height: 30px" /> -->
      <div class="menu-item" @click="changeMode('player')">
        <IconFullScreenPlay class="icon" /> {{ $t('preview') }}
      </div>
      <Divider type="vertical" style="height: 30px" />
      <div class="menu-item" v-tooltip="$t('export')"
        @click=" platform === 'wx' && sfType === '0' ? wxdc() : exportPPTX(selectedSlides, masterOverwrite, ignoreMedia, true)">
        <IconDownload class="icon" />{{ $t('download') }}
      </div>
      <!-- <div class="menu-item" v-tooltip="'导出'" @click=" exportPPTX(selectedSlides, masterOverwrite, ignoreMedia, true)">
        <IconDownload class="icon" />下载
      </div> -->
    </div>
    <FullscreenSpin :loading="exporting || exportingCtrl" :tip="$t('loading') + '...'" />
    <FullscreenSpin :loading="exportingexp" :tip="$t('exporting') + '...'" />
    <Modal :visible="!!dialogForExport" :width="400" @closed="closeExportDialog()">
      <ExportDialog />
    </Modal>
  </div>
</template>

<script lang="ts" setup>
const thumbnailListRef = ref<HTMLElement>();
/* 数据交互 */
import browser from '@/utils/browser'
import hintImg from '../../assets/image/ts.png'
let sfType: string | null;
let platform: string | null;
let Appid: string | null
let templateId: string | null
const exportingCtrl = ref(true) //测试为false 正式改为true

const isCanIExportIt = ref(false)//测试为true 正式改为false
// const getAppParameters = () => {
// 	console.log(browser().ios, "<=========当前平台=========>");

// };

const sendUserInfo = (encryptedData: string) => {
  storingBasicInformation(encryptedData);
};

const userInfoCallBack = (encryptedData: string) => {
  storingBasicInformation(encryptedData);
};

/**
 * 请求ppt生成 流式
 * 安卓调用回调
 * @param encryptedData  //安卓回传的加密请求参数
 */
const storingBasicInformation = (encryptedData: string) => {
  console.log(encryptedData, "base");
  const controller = startSSE(encryptedData);
  onBeforeUnmount(() => {
    if (controller) {
      controller.abort();
    }
  });
};

import { obtainPptTemplate, getWorksJson } from '@/http/api';
import { decryptPpt } from "@/utils/crypto"
import type { ApiResponse } from '@/http/api'; // 使用 type-only import
const data = ref<ApiResponse | null>(null);

// const fetchDataFromApi = async () => {

// };


/**
 * 小程序模版预览特殊处理
 *
 */
const wxdc = () => {
  console.log('执行了特殊导出');
  try {
    // wx.miniProgram.postMessage({
    //   data: templateId,
    // });

    try {
      wx.miniProgram.redirectTo({
        url: "/pages_template/templateDaochu/templateDaochu",
      });
    } catch { }
    {
    }

    try {
      tt.miniProgram.redirectTo({
        url: "/pages_template/templateDaochu/templateDaochu",
      });
    } catch { }
    {
    }
  } catch { } {

  }
}


/**
 * 安卓调用 模板预览
 * @param encryptedData  //安卓回传的加密请求参数
 */
const getPreviewJSON = async (encryptedData: string) => {
  console.log("====jsonData====", encryptedData);
  exportingCtrl.value = true
  isCanIExportIt.value = true
  try {
    const params = `x7oYfv4kPmBIbYnEFyBkIq3c2+B64cCgvjFEK3RUHesRHMaadYl4UNXEt58V14NgbQOKe08+8Swog2vuBECuv8+yz+LM55FstPvZlP4lyLVmg+7HxfINb1mrrBEEXuurxUTtopXLDJV2PPlbDOnF9Obod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Lh6BSAy2BZv7IMOo95zdw7cTq3FWx3RUHEhH9tcU5GUbstRpZTKWuNN42Csjy9LL/IdRXxtwPTMGakiC4Qbx/80rxxAzHFNBa8Mh2iC0u15xhPVJepFB0Gydk2eZRpFif6qO3Skrteig1uI5F6pDILSVlZ43ienEQ6QqGv9+84YVm5egIvmU56mtJ0BDFHWVvLyPhD9j1xyDohjZq4SQnHMmIFuXTlcavr5j/oEAZuJTsgmcm3Ui/rcQslRnkWA8wjVDlEqkxn13WOiRxv68v4epN3fJggcYyrys3yxltolt8HK9Uw66qiCOfHTBYo8efMwfxUydNvqYPzfXtEI2938oiHbtfRxSyjB7+IQcaxBa6Y6g6esQu3sB5+CFlCKdZLa+2vMo16hROq9sVVQ+zi65ST/KhP3plyIXKlMXwqx6saSwQE4kiqQ7WqVV65mPzsxj9h8ryw8rQ2QfvmGDDBQ04RIRUgu52y0ihpl8Alla+WXIWSC2nwZbolOLNc2KE8bUtJhUKDYDEv7cd9DwlLRqg0kLxGCgsooSER8R8dvfPhNZjfOpgxAFGO/3S+DM2e41BwLZhCh5rV6KqJ3Ev6BKyA2f+xlykLdZ3uyM97/D+UcOeomDcb4r429bZuev91ZoFKWD2MlQVKllOWKM2O8jL5AAFrVh5cZfgGKjK4dLs0DIweftC3DAT1RIBZnsq1o3Fdgd4L3sJvnBJuHo/QyrC/XTqeUoD17avoCaXnt6ypfxaGxd3IauXt0r1jqfs9FYleWXfsMBn3QkHXiakJBFifOIkQ8BlE/YjS0Wg=`;
    data.value = await obtainPptTemplate(encryptedData);
    exportingCtrl.value = false
    if (data.value.code != 200) {
      if (browser().ios) {
        /**
      * ios调用
      */
        try {
          // 示例：调用 jointQQ 方法
          if (jsCallNative.endFlow) {
            console.log("endFlow");
            jsCallNative.endFlow(data.value.code, data.value);
          } else {
            console.error('jsCallNative.endFlow 方法不可用');
          }
        } catch { } {

        }
      } else {
        /**
       * 安卓调用
       */
        // try {
        //   trans_obj.endFlow(data.value.code, data.value);
        // } catch { } {

        // }
      }
      console.log(data.value, "====返回报错=====");
      exportingCtrl.value = false
      if (e.message === '次数已用完') {
        ElMessage({
          message: t('err'),
          type: 'error',
          duration: 4000
        })
        return
      } else {
        ElMessage({
          message: e.message,
          type: 'error',
          duration: 4000
        })
      }

      return;
    } else {
      let datapptparams: any = decryptPpt(params as string, '1053', Appid || '')
      if (datapptparams) {
        datapptparams = JSON.parse(datapptparams)
        console.log(datapptparams.param.outlineId, '===解密====outlineId');
        sessionStorage.setItem("base", JSON.stringify(datapptparams.base));
        sessionStorage.setItem("outlineId", datapptparams.param.outlineId);
        sessionStorage.setItem("taskId", datapptparams.param.taskId);
      }

      if (browser().ios) {
        /**
      * ios调用
      */
        try {
          // 示例：调用 jointQQ 方法
          if (jsCallNative.endFlow) {
            console.log("endFlow");
            jsCallNative.endFlow(200, 'success');
          } else {
            console.error('jsCallNative.endFlow 方法不可用');
          }
        } catch { } {

        }
      } else {
        /**
       * 安卓调用
       */
        try {
          trans_obj.loadSuccess(200, 'success');
        } catch { } {

        }
      }
    }
    // console.log(data.value.data.results, '===获取预览模板====');
    importJSONurl(data.value.data.results);
  } catch (error) {
    exportingCtrl.value = false
    console.error('Failed to fetch data:', error);
  }
};

/**
 * 小程序
 * 安卓调用 作品预览
 * @param encryptedData  //安卓回传的加密请求参数
 */
const previewWorkID = async (encryptedData: string) => {
  exportingCtrl.value = true
  isCanIExportIt.value = true
  console.log('作品预览');

  let datapptparams: any = decryptPpt(encryptedData as string, '1061', Appid || '')
  if (datapptparams) {
    datapptparams = JSON.parse(datapptparams)
    console.log(datapptparams.param.outlineId, '===解密====outlineId=====1061');
    sessionStorage.setItem("base", JSON.stringify(datapptparams.base));
    sessionStorage.setItem("outlineId", datapptparams.param.outlineId);
    sessionStorage.setItem("taskId", datapptparams.param.taskId);
  }

  try {
    const params = `x7oYfv4kPmBIbYnEFyBkIq3c2+B64cCgvjFEK3RUHesRHMaadYl4UNXEt58V14NgbQOKe08+8Swog2vuBECuv8+yz+LM55FstPvZ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bLUthkBSXb6A4NDBBIwopYZw6zX6sKQDerqboYw6aEWAaPN8l8g3bLh6BSAy2BZv7IMOo95zdw7cTq3FWx3RUHEhH9tcU5GUbstRpZTKWuNN42Csjy9LL/IdRXxtwPTMGakiC4Qbx/80rxxAzHFNBa8Mh2iC0u15xhPVJepFB0Gydk2eZRpFif6qO3Skrteig1uI5F6pDILSVlZ43ienEQ6QqGv9+84YVm5egIvmU56mtJ0BDFHWVvLyPhD9j1xyDohjZq4SQnHMmIFuXTlcavr5j/oEAZuJTsgmcm3Ui/rcQslRnkWA8wjVDlEqkxn13WOiRxv68v4epN3fJggcYyrys3yxltolt8HK9Uw66qiCOfHTBYo8efMwfxUydNvqYPzfXtEI2938oiHbtfRxSyjB7+IQcaxBa6Y6g6esQu3sB5+CFlCKdZLa+2vMo16hROq9sVVQ+zi65ST/KhP3plyIXKlMXwqx6saSwQE4kiqQ7WqVV65mPzsxj9h8ryw8rQ2QfvmGDDBQ04RIRUgu52y0ihpl8Alla+WXIWSC2nwZbolOLNc2KE8bUtJhUKDYDEv7cd9DwlLRqg0kLxGCgsooSER8R8dvfPhNZjfOpgxAFGO/3S+DM2e41BwLZhCh5rV6KqJ3Ev6BKyA2f+xlykLdZ3uyM97/D+UcOeomDcb4r429bZuev91ZoFKWD2MlQVKllOWKM2O8jL5AAFrVh5cZfgGKjK4dLs0DIweftC3DAT1RIBZnsq1o3Fdgd4L3sJvnBJuHo/QyrC/XTqeUoD17avoCaXnt6ypfxaGxd3IauXt0r1jqfs9FYleWXfsMBn3QkHXiakJBFifOIkQ8BlE/YjS0Wg=`;
    data.value = await getWorksJson(encryptedData);
    exportingCtrl.value = false
    if (data.value.code != 200) {
      if (browser().ios) {
        /**
      * ios调用
      */
        try {
          // 示例：调用 jointQQ 方法
          if (jsCallNative.endFlow) {
            console.log("endFlow");
            jsCallNative.endFlow(data.value.code, data.value);
          } else {
            console.error('jsCallNative.endFlow 方法不可用');
          }
        } catch { } {

        }
      } else {
        /**
       * 安卓调用
       */
        try {
          trans_obj.endFlow(data.value.code, data.value);
        } catch { } {

        }
      }
      console.log(data.value, "====返回报错2=====");
      exportingCtrl.value = false
      if (e.message === '次数已用完') {
        ElMessage({
          message: t('err'),
          type: 'error',
          duration: 4000
        })

        return
      } else {
        ElMessage({
          message: e.message,
          type: 'error',
          duration: 4000
        })
      }

      return;
    } else {
      console.log(data.value, '===获取作品预览====');
      sessionStorage.setItem("upgrade", JSON.stringify(data.value.data.upgrade));
      importJSONurl(data.value.data.results);

      if (!!data.value.data.fileurl) {
        sessionStorage.setItem("workLink", data.value.data.fileurl);
      }

      if (browser().ios) {
        /**
      * ios调用
      */
        try {
          // 示例：调用 jointQQ 方法
          if (jsCallNative.endFlow) {
            console.log("endFlow");
            jsCallNative.endFlow(200, 'success');
          } else {
            console.error('jsCallNative.endFlow 方法不可用');
          }
        } catch { } {

        }
      } else {
        /**
       * 安卓调用
       */
        try {
          trans_obj.endFlow(200, 'success');
        } catch { } {

        }
      }
    }
  } catch (error) {
    exportingCtrl.value = false
    console.error('Failed to fetch data:', error);
  }
};
/* 数据交互 */

const scrollToBottom = () => {
  if (thumbnailListRef.value) {
    console.log(thumbnailListRef.value.scrollTop, 'thumbnailListRef.value', thumbnailListRef.value.scrollHeight);
    thumbnailListRef.value.scrollTop = thumbnailListRef.value.scrollHeight
  }
}

/* 流式返回json */
import { fetchEventSource } from "@microsoft/fetch-event-source";
import { ref, onMounted, onBeforeUnmount, computed, watch, nextTick } from "vue";
import { ElMessage } from 'element-plus';
import i18n from '@/i18n'

const t = i18n.global.t;
const messages = ref<string[]>([]);
const startSSE = (params: string) => {
  if (!Appid) {
    exportingCtrl.value = false
    ElMessage({
      message: 'Appid为空',
      type: 'error',
      duration: 4000
    })
    console.log(Appid, 'Appid为空');
    return
  }

  let datapptparams: any = decryptPpt(params as string, '1053', Appid || '')
  if (datapptparams) {
    datapptparams = JSON.parse(datapptparams)
    console.log(datapptparams.param.outlineId, '===解密====outlineId');
    sessionStorage.setItem("base", JSON.stringify(datapptparams.base));
    sessionStorage.setItem("outlineId", datapptparams.param.outlineId);
    sessionStorage.setItem("taskId", datapptparams.param.taskId);
  }

  const controller = new AbortController();
  // const fetchUrl = `https://ser.aixiezuo888.com/chat/api/c=1038&v=4&a=${'webaixz'}`
  // const fetchUrl = `http://and2.mypeiyin.com/chat/api/c=1053&v=4&a=aibkzj`
  // const fetchUrl = `/chatBase/chatBase/api/c=1053&v=4&a=${Appid}`; //测试环境
  // const fetchUrl = `/chatBase/chat/api/c=1053&v=4&a=${Appid}`;
  const fetchUrl = `/chatBase/aippt/api/c=1053&v=4&a=${Appid}`;
  const opts = {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
    },
    body: params,
  };
  let ToAdd = 0;
  const cacheArray: any = [];
  let isSSEClosed = false;
  const outputInterval = 1800; // 3秒

  const timer = setInterval(() => {
    if (ToAdd < cacheArray.length) {
      if (ToAdd === 0) {
        importJSON(cacheArray[ToAdd], true);
      } else {
        importJSON(cacheArray[ToAdd], false);
      }
      ToAdd++;
      exportingCtrl.value = false
      nextTick(() => {
        scrollToBottom()
      })
    } else if (isSSEClosed) {
      // 如果 SSE 已关闭并且所有数据已处理完，则清除定时器
      clearInterval(timer);

      if (browser().ios) {
        /**
      * ios调用
      */
        try {
          // 示例：调用 jointQQ 方法
          if (jsCallNative.endFlow) {
            console.log("endFlow");
            jsCallNative.endFlow(200, 'close');
          } else {
            console.error('jsCallNative.endFlow 方法不可用');
          }
        } catch { } {

        }
      } else {
        /**
       * 安卓调用
       */
        try {
          trans_obj.endFlow(200, 'close');
        } catch { } {

        }
      }
      isCanIExportIt.value = true
    }
  }, outputInterval);

  fetchEventSource(fetchUrl, {
    ...opts,
    openWhenHidden: true,
    signal: controller.signal,
    onopen(response) {
      // 处理连接打开时的逻辑
      if (response.ok && response.status === 200) {
        //exportingCtrl.value = false
        console.log("SSE 连接已打开");
      } else {
        console.error("无法打开 SSE 连接", response);
      }
    },

    onmessage(event) {
      const e = JSON.parse(event.data);

      //     if (url !== sessionStorage.getItem("indexUrl") && url) {
      //   await importPPTXFile("", url);

      // }
      sessionStorage.setItem("isRenderingComplet", 'true');

      if (e.code !== 200) {
        if (browser().ios) {
          /**
           *
            * ios调用
           */
          try {
            // 示例：调用 jointQQ 方法
            if (jsCallNative.endFlow) {
              console.log("endFlow");
              jsCallNative.endFlow(400, e.message);
            } else {
              console.error('jsCallNative.endFlow 方法不可用');
            }
          } catch { } {

          }
        } else {
          /**
         * 安卓调用
         */
          try {
            trans_obj.endFlow(400, e.message);
          } catch { } {
          }

        }
        console.log(e, "====返回报错3=====");
        exportingCtrl.value = false
        if (e.message === '次数已用完') {
          ElMessage({
            message: t('err'),
            type: 'error',
            duration: 4000
          })

          return
        } else {
          ElMessage({
            message: e.message,
            type: 'error',
            duration: 4000
          })
        }

        return;
      }
      // console.log(JSON.stringify(e.data), 'json  ===每页===')
      cacheArray.push(e.data);
      // console.log(e, "====流式=====");
    },

    onerror(err) {
      exportingCtrl.value = false

      if (browser().ios) {
        /**
      * ios调用
      */
        try {
          // 示例：调用 jointQQ 方法
          if (jsCallNative.endFlow) {
            console.log("endFlow");
            jsCallNative.endFlow(400, 'error');
          } else {
            console.error('jsCallNative.endFlow 方法不可用');
          }
        } catch { } {

        }
      } else {
        /**
       * 安卓调用
       */
        try {
          trans_obj.endFlow(400, 'error');
        } catch { } {

        }
      }

      console.error("SSE Error:", err);
      isSSEClosed = true; // 标记 SSE 已关闭
    },

    onclose() {

      console.log("SSE 连接已关闭");
      isSSEClosed = true; // 标记 SSE 已关闭

    },
  });

  // 保存controller以便在onBeforeUnmount钩子中使用
  return controller;
};

/* 流式返回json */

import ExportDialog from "../Editor/ExportDialog/index.vue";

import Modal from "@/components/Modal.vue";
import FullscreenSpin from "@/components/FullscreenSpin.vue";
// import { onMounted, ref } from 'vue'
import { storeToRefs } from "pinia";
import { useMainStore, useSlidesStore } from "@/store";
import useLoadSlides from "@/hooks/useLoadSlides";
import type { Mode } from "@/types/mobile";
import useImport from "@/hooks/useImport";
import type { DialogForExportTypes } from "@/types/export";

import ThumbnailSlide from "@/views/components/ThumbnailSlide/index.vue";
import Divider from "@/components/Divider.vue";
import useExport from "@/hooks/useExport";
import { json } from 'stream/consumers';
import type { lte } from 'lodash';

// defineProps<{
//   changeMode: (mode: Mode) => void;
// }>();

const props = defineProps<{
  changeMode: (mode: Mode) => void
}>()

const executiveEdit = () => {
  console.log('执行调用editor');

  props.changeMode('editor')
}

const {
  importSpecificFile,
  importPPTXFile,
  exporting,
  importJSON,
  importJSONurl,
} = useImport();
const { slides } = storeToRefs(useSlidesStore());
const { slidesLoadLimit } = useLoadSlides();
const mainMenuVisible = ref(false);
const mobileRef = ref<HTMLElement>();
const screenWidth = ref(0);
const mainStore = useMainStore();
const { exportPPTX, exportingexp, notifyMiniProgram } = useExport();

const ignoreMedia = ref(true);
const masterOverwrite = ref(true);
const { currentSlide } = storeToRefs(useSlidesStore());
const rangeType = ref<"all" | "current" | "custom">("all");
const closeExportDialog = () => mainStore.setDialogForExport("");
const { dialogForExport, showSelectPanel, showSearchPanel, showNotesPanel } =
  storeToRefs(mainStore);
const range = ref<[number, number]>([1, slides.value.length]);

const selectedSlides = computed(() => {
  if (rangeType.value === "all") return slides.value;
  if (rangeType.value === "current") return [currentSlide.value];
  return slides.value.filter((item, index) => {
    const [min, max] = range.value;
    return index >= min - 1 && index <= max - 1;
  });
});

const setDialogForExport = (type: DialogForExportTypes) => {
  console.log("执行了", type);

  // mainStore.setDialogForExport(type)
  // mainMenuVisible.value = false
};


/**
 *
 * 安卓端调用执行导出
 */
const startDownload = () => {
  console.log("====执行导出ppt====");
  exportPPTX(selectedSlides.value, masterOverwrite.value, ignoreMedia.value, true)
};


watch(
  slides,
  (newSlides, oldSlides) => {
    console.log("Slides changed:", JSON.stringify(newSlides));
  },
  { deep: true }
);

onMounted(async () => {
  window.sendUserInfo = sendUserInfo; // 给安卓原生调用
  window.getPreviewJSON = getPreviewJSON;// 给安卓原生调用
  window.startDownload = startDownload; // 给安卓原生调用
  window.previewWorkID = previewWorkID; // 给安卓原生调用
  window.userInfoCallBack = userInfoCallBack; // 给 iOS 原生调用
  window.executiveEdit = executiveEdit

  if (!mobileRef.value) return;
  screenWidth.value = mobileRef.value.clientWidth;
  const urlParams = new URLSearchParams(window.location.search);

  /**
   *
   *  流式或预览 区分 0模板预览 1流式 2作品预览
   */
  sfType = urlParams.get("type");
  if (!sfType) {
    exportingCtrl.value = false
    ElMessage({
      message: '请求失败',
      type: 'error',
      duration: 4000
    })
  }

  /**
   *
   *
   */
  platform = urlParams.get("platform")
  if (!platform) {
    exportingCtrl.value = false
    ElMessage({
      message: '请求失败',
      type: 'error',
      duration: 4000
    })
  }
  console.log(platform, "platform");

  /**
   *
   * 获取端appid
   */
  Appid = urlParams.get("appid")
  if (Appid) {
    sessionStorage.setItem("Appid", Appid);
  }


  /**
   *
   *
   *
   */
  const url = urlParams.get("url"); // Assuming 'url' is the query parameter containing the URL of the PPTX file
  console.log(
    url,
    "=====获取地址栏信息url======",
    sessionStorage.getItem("indexUrl")
  );
  if (url !== sessionStorage.getItem("indexUrl") && url) {
    await importPPTXFile("", url);
    sessionStorage.setItem("indexUrl", url);
  }

  /**
   *
   *
   *
   */
  const jsonUrl = urlParams.get("jsonUrl"); // Assuming 'url' is the query parameter containing the URL of the PPTX file
  console.log(
    jsonUrl,
    "=====获取地址栏信息jsonUrl======",
    sessionStorage.getItem("jsonUrl")
  );
  if (jsonUrl !== sessionStorage.getItem("jsonUrl") && jsonUrl) {
    // await importPPTXFile("", jsonUrl);
    importJSONurl(jsonUrl);
    sessionStorage.setItem("indexUrl", jsonUrl);
  }

  /**
   *
   *
   */
  let params = urlParams.get("params");
  if (params) {
    params = decodeURIComponent(params);
    // console.log(params, "params----------");

    if (sessionStorage.getItem("base")) {
      exportingCtrl.value = false
      isCanIExportIt.value = true
      console.log('已经执行过了');
      return
    }

    if (platform === 'wx') {
      switch (sfType) {
        case '0':
          getPreviewJSON(params)
          break;
        case '1':
          if (sessionStorage.getItem("isRenderingComplet") == 'true') {
            return
          }
          const controller = startSSE(params);
          onBeforeUnmount(() => {
            if (controller) {
              controller.abort();
            }
          });
          break;
        case '2':
          previewWorkID(params)
          break;
        default:
          break;
      }
    }
  }

  /**
   *
   * <=========交互调用=========>
   */
  try {
    if (sessionStorage.getItem("base")) {
      // exportingCtrl.value = false
      console.log('已经执行过了app');
      return
    }

    if (browser().ios) {
      console.log("<=========iOS 交互调用=========>");
      try {
        // 示例：调用 jointQQ 方法
        if (jsCallNative.loadJosn) {
          console.log("1111111");
          jsCallNative.loadJosn(sfType);
        } else {
          console.error('jsCallNative.jointQQ 方法不可用');
        }
      } catch { } {

      }


    } else {
      console.log("<=========安卓 交互调用=========>");
      // trans_obj.getUserInfos();
      trans_obj.loadJosn(sfType);
    }
  } catch { } {

  }


  // const controller = startSSE('2inM9MYkN8+bwjPZ+dpv0dRV/eysIbXW53mXkpljnsshU66ELfGB3xQxcFrrN3pAAruQwLHX+PEzvlEXlsuxYhIerrpIV1ZexQfDoryUoumL+2PcWJXb9Qzf7x/HnBTI/+UPqQC/BTtLAafo32Ks9vySESZBHbQcDQtK/Tm4InIfCQ6PpeSJ3nl3W5XpA17ZoVe/+n9GND2W8OkAnl0sF+bs4UjIJslilP2t1mEHKzuMEEHDLNlFIV0aUMFOJa1ZO0eXNb0qxNQ+y3IFfD0lwL3/bBFyHSOB5g92oGrwa1rwtkDw6TE5nYvOZMhCb+n/HAihbKNrjam0bQT5w7kQYfqRcREzLH3yj7KDbGJJ0HnNEglu4qmfnHid89AAZ4X5WmojLN18u4XGzzecX8VSj8SnyZRxxfbpQIoBjGsAciGoJD30PqQXpGLxMQFa7oRrjUlWc+pmBUuvzb9kZY5rOP0DCUkaiiT1wcdGoufXkt0bu8j8iC+Un4qKpV769xbfcXsScPgTvRvsachoj9Uma7giHKq/ZUnMMayQW7qDwhEqXKNGvH1WBqn57sG7KkCvdeFReKPwVFrgua9iGt8CtOgMhtKhZhZAhnGC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L4dq1EaV4OLkqfX43XewHezDhDWcyuNtHranFC+59a12h2D6vxZ17782QfRRDeKQKlQFXjXcvarCdB2yA8zBRkDWrYDps7sbGQUXKvpBtLyDGrMN3jrjnEeNHmqgbDoXzZIcWFkdUeb2+rfXOZN0+9AH0NfE0Wvmsd67H3y9K5VWLUfg8I5O4I/I4YMThefFaZbySz4vLdO+iKATMFaA4UhZV6fe75FJcjylrV2j98ea1XO/ALPTLVVw114090gzV6v8jyXvG3oFthwLMfT5e00uJLR8qRspbE0a5tJlFro/QTyWmgeiFKmxr4WUnCWJCpXHboUeNE+lTyAewkKc93tA2KZMoDR5I+PpLWzZK4=');
  // onBeforeUnmount(() => {
  //   if (controller) {
  //     controller.abort();
  //   }
  // });

  // getPreviewJSON('CkDzoy5z708vgGIdxymO6TrhDUPttsRRydidWy0lLvFEb93Y4J2mRCjCxtvp5BK+jW9DoJMq2wIkBYRgAnjn/sVcXbFYTnDfzTZUPoHMyEXHymk80GJkkPxjuN0HNBzR7F/KDiUQ3JPRQaB6Y25Y+Bbib7954rFThvow7YY8f4QTCgcDbkoEOftWD5w4sT/CAOZHalfBKdALM408+0y3/uFcNI1eiX7ltgc/G1c7tLm/M8O+ae7Rlnz/2iDSJ709rXCqCk3YocjF8D5+7BX9chW7qczcXqsoIGcuqJ2y89+Kf+uAwQzaipXgaJmmDbj/Y+9fJU/mOBh2lxp1O6JV8uw7f2bUs7wRGNQxU0x4u6S2Bz8bVzu0uZKMFJNEU8cOWGOq+mARcA8RDDd7NkOfH8c15BZR9xvN4drauzYa50y8/UsZ8Fw1dWCdRvtN3ulqkowUk0RTxw4PuvCdGwIeAyQBWqDjXAXehvow7YY8f4QyNnHvf0Pp/nOJs4nWPeftQxcSWa5EZi53NKL+q/0RSH3ZOUeSsnZ0FTh+HQ+l0qNm2G+oAbCHKzxpMfplkRl30OhgrgtjbJK94T7xdi+C6HsT/z/Ezjo6muOrx8fkzFstlPoSmHYzCsti/geC7kYY0Q/CAyLIzPZYkPIwB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qofLQjd90wNHVfwSiN1yuVDMcQk/vfMNjm5ezO6rR8rSquk/O526Cb57homwly7sMn7PNlBY2RUwJUYsw8CxNhsKAM7MPaZ4i4Po/ZAol+gNuDnYKqXQ8Qc6ZlXRot2mTzERXqXSlFdcZEIG0jn8wNCoAwvLqrBadMsgbfPfytrDzP7CH4WmDfeiRTP+zs5RRBUe9fMGWDZg7SEXfBn3KQj9aepuAWejLlQV1N9P/Q/jVEzDnlptJ5cA==')
});
</script>

<style lang="scss" scoped>
.mobile-preview {
  height: 100%;
  background-color: #f9f9f9;
}

.thumbnail-list_hei {
  height: calc(100%);
}

.thumbnail-list_heiwx {
  height: calc(100% - 80px);
}

.thumbnail-list {
  // height: calc(100% - 50px);
  // height: calc(100%);
  padding: 10px;
  overflow: auto;
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
}

.thumbnail-item {
  display: flex;
  justify-content: center;
  align-items: center;
  box-shadow: 0 0 15px 0 rgba(0, 0, 0, 0.1);
  position: relative;

  &.thumbnail-item {
    margin-bottom: 10px;
  }

  .page_number {
    position: absolute;
    right: 5px;
    bottom: 5px;
    width: 20px;
    height: 20px;
    background: rgba(0, 0, 0, 0.5);
    color: #fff;
    text-align: center;
    line-height: 20px;
    border-radius: 5px;
    z-index: 1;
    font-size: 12px;
    font-weight: 400;
  }
}

.hint {
  display: flex;
  align-items: center;
  background: #ffffff;
  font-size: 14px;
  height: 30px;
  padding-left: 10px;
  line-height: 1;

  .iconA {
    margin-right: 5px;
    display: block;
    width: 20px;
    height: 20px;
    font-size: 20px;
  }
}

.menu {
  height: 50px;
  position: relative;
  box-shadow: 0 -2px 4px 0 rgba($color: #333, $alpha: 0.05);
  background: #fff;
  display: flex;
  justify-content: center;
  align-items: center;

  .menu-item {
    width: 50%;
    height: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    font-size: 13px;

    .icon {
      margin-right: 8px;
      font-size: 18px;
    }
  }
}
</style>
